/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: 北京银杉金服科技有限公司
 * 系统版本: 1.0.0
 * 开发人员: zhangfb
 * 开发时间: 2018/9/8 20:26
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.hyacinth.security;

import com.hyacinth.constant.GlobalConstant;
import com.hyacinth.entity.User;
import com.hyacinth.util.ThreadLocalMap;
import com.hyacinth.util.XaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
@Slf4j
@Component
public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {

    private final SpringSessionRegistry sessionRegistry;

    @Autowired
    public CustomLogoutSuccessHandler(SpringSessionRegistry sessionRegistry) {
        this.sessionRegistry = sessionRegistry;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Object userDetails = authentication.getPrincipal();
        if (null != userDetails && !GlobalConstant.ANONYMOUS_USER.equals(userDetails)) {
            User authUser = (User) userDetails;
            List<SessionInformation> sis = sessionRegistry.getAllSessions(authUser, false);
            if (!XaUtils.isEmpty(sis)) {
                for (SessionInformation si : sis) {
                    si.expireNow();
                    if (si.isExpired()) {
                        sessionRegistry.removeSessionInformation(si.getSessionId());
                    }
                }
            }
            log.info("用户（" + authUser.getName() + "）登出系统！");
        }
        ThreadLocalMap.remove();
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("登出成功");
    }
}
